package com.fresh.bus.chat.business;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.util.TokenBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fresh.bus.chat.domain.BaseLog;
import com.fresh.bus.chat.domain.TreeLog;
import com.fresh.bus.chat.domain.UserLog;
import com.fresh.bus.chat.util.DateUtil;

public class BaseLogService {
	protected static final Logger log = LoggerFactory
			.getLogger(BaseLogService.class);

	protected ObjectMapper objectMapper = new ObjectMapper();
	protected TokenBuffer buffer = new TokenBuffer(null);

	public List<BaseLog> readLog(String json) throws Exception {
		List<BaseLog> list = new ArrayList<BaseLog>();
		JsonFactory f = objectMapper.getJsonFactory();
		JsonParser jp = f.createJsonParser(json);
		// advance stream to START_ARRAY first:
		jp.nextToken();
		// and then each time, advance to opening START_OBJECT
		while (jp.nextToken() == JsonToken.START_OBJECT) {
			BaseLog log = objectMapper.readValue(jp, BaseLog.class);
			// process
			// after binding, stream points to closing END_OBJECT
			list.add(log);
		}
		return list;
	}

	protected String appendLog(String json, BaseLog baseLog) {
		String result = "[]";
		try {
			ArrayNode root = (ArrayNode) objectMapper.readValue(json,
					JsonNode.class);
			String jsonString = objectMapper.writeValueAsString(baseLog);
			JsonNode node = objectMapper.readValue(jsonString, JsonNode.class);
			root.insert(0, node);
			int len = root.size();
			if(len > 60){
				root.remove(len-1);
			}
			result = objectMapper.writeValueAsString(root);
		} catch (Exception e) {
			log.error("", e);
		}
		return result;
	}

	public String getBaseLog(List<BaseLog> list) throws Exception {
		JsonNode root;
		String jsonText;
		JsonFactory f = objectMapper.getJsonFactory();
		StringWriter sw = new StringWriter();
		JsonGenerator g = f.createJsonGenerator(sw);
		g.writeStartArray();
		for (BaseLog log : list) {
			objectMapper.writeValue(buffer, log);
			root = objectMapper.readTree(buffer.asParser());
			jsonText = objectMapper.writeValueAsString(root);
			g.writeString(jsonText);
		}
		g.writeEndArray();
		return sw.toString();
	}
}
